﻿#include <opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<iostream>
#include <string.h>
#include"aiai/aiai_fileread.hpp"
#include"aiai/aiai_filewrite.hpp"
#include "h264encoder.hpp"
#include "h264decoder.hpp"
#include <opencv2/opencv.hpp>

using namespace cv;
using namespace std;

int main()
{
    aiai_filewrite fw("./test.h264");
    int H = 512;
    int W = 640;
    aiai_fileread file("/home/aiai/test_yuyv_640_512.dat");
    cv::Mat image(H,W,CV_8UC2);
    cv::Mat image1(H,W,CV_8UC3);
    unsigned char *data = (unsigned char*)malloc(H*W*2);
//    while(true){
//        if(0>=file.read(data,H*W*2)){
//            return 0;
//        }
//        memcpy(image.data,data,H*W*2);
//        cv::cvtColor(image,image1,COLOR_YUV2RGB_YUYV);
//        imshow("test",image1);
//        waitKey(100);
//    }
//    file.close();

    cv::Mat frame;
    cv::Mat dst;
    h264Encoder h264;
    AvH264EncConfig conf;
    conf.width = W;
    conf.height = H;
    conf.gop_size = 10;
    conf.max_b_frames = 0;
    conf.frame_rate = 6;
    h264.Init(conf);


    CH264Decoder m_h264Decoder;
    m_h264Decoder.initial();

    int jpeg_quality = 75;
    std::vector<int> params;
    params.push_back(cv::IMWRITE_JPEG_QUALITY);
    params.push_back(jpeg_quality);

    cv::Mat cvDst;
    int nWaitTime =100;
    while (true)
    {
        if(0>=file.read(data,H*W*2)){
            return 0;
        }
        memcpy(image.data,data,H*W*2);
        cv::cvtColor(image,image1,COLOR_YUV2BGR_YUYV);
        frame = image1;
        if( frame.empty() )
            break;
        cv::imshow("src",frame);
        cv::Mat _frame;
        cv::resize(frame,_frame,cv::Size(W,H),0,0);

        double timePoint1 = cv::getTickCount();

        std::vector<uchar> jpgSize;
        cv::imencode(".jpg", _frame, jpgSize, params);

        double timePoint2 = cv::getTickCount();

        cvDst = cv::imdecode(jpgSize,cv::IMREAD_COLOR);
        cv::imshow("cvdecode",cvDst);


        // do encode
        AVPacket *pkt = h264.encode(frame);
        int size = pkt->size;
        uchar* data = nullptr;
        data = pkt->data;
//        fw.write(data,pkt->size);
        m_h264Decoder.decode(data,size,dst);
        cv::imshow("decode",dst);

        double timePoint3 = cv::getTickCount();


        cv::Mat diff = dst - frame;
        cv::imshow("diff",diff);//查看编解码前后图像是否有差异



        printf("cv::encode size:%d Fps:%.2f, h264 encode size:%d,Fps:%.2f\n",
                jpgSize.size(),cv::getTickFrequency()/(timePoint2-timePoint1),
                size,cv::getTickFrequency()/(timePoint3-timePoint2));

        char chKey = cv::waitKey(nWaitTime);
        //ESC
        if (27 == chKey)break;
        else if (' ' == chKey) nWaitTime = !nWaitTime;
    }
}
